<template>
  <div class="dialog">
    <el-dialog title="审批" :visible="show" @update:visible="closeDialog" v-loading="loading">
      <details-form
        ref="detailsForm"
        :validateFields="detailsFormValidate"
        :isFromMessage="isFromMessage"
        @derogatory-categories-change="handleDisabledBtnsChange">
      </details-form>
      <div slot="footer" class="dialog-footer">
        <btns :disabledBtns="disabledBtns"
              @sleep="handleSleep"
              @reject="handleReject"
              @next="handleNext"
              @done="handleDone"
              @adopted="handleAdopted">
        </btns>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {mapState, mapGetters, mapActions} from 'vuex'
  import DetailsForm from './detailsForm'
  import Btns from './btns'
  import {
    getDepartment,
    userOpnCenterNext,
    userOpnCenterVisit,
    saleHQNext,
    saleHQVisit
  } from '@/service/getData'

  export default {
    components: {
      Btns,
      DetailsForm
    },
    props: {
      show: {
        type: Boolean,
        default: false
      },
      baseInfo: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        opnCode: '',
        disabledBtns: [],
        loading: false,
        detailsFormValidate: {
          branchCompany: true
        }
      }
    },
    computed: {
      ...mapState({
        platformType: state => state.disparageManage.platformType,
        ctype: state => state.disparageManage.ctype,
        currentOrderCtype: state => state.disparageManage.currentOrderCtype,
        currentOrderStatus: state => state.disparageManage.currentOrderStatus,
        currentOrderDetails: state => state.disparageManage.currentOrderDetails
      }),
      ...mapGetters([
        'userType',
        'disparageType'
      ]),
      // 是否分公司管理员
      isFGLY() {
        return this.userType === this.platformType.FGLY
      },

      // 是否销司总部
      isXSZB() {
        return this.userType === this.platformType.XSZB
      },

      // 是否用户运营中心
      isYYZX() {
        return this.userType === this.platformType.YYZX
      },

      // 来源message
      isFromMessage() {
        const reason = this.currentOrderDetails.derogatoryReason || ''
        return /^\[/.test(reason)
      }
    },
    methods: {
      closeDialog(value) {
        this.disabledBtns = []
        this.$store.commit('SET_CURRENTORDERDETAILS', {})
        this.$emit('update:show', false)
      },

      // 设置禁用按钮
      handleDisabledBtnsChange(value) {
        const items = ['0', '5', '6']
        if (items.indexOf(value) > -1) {
          this.disabledBtns = ['休眠', '下发']
        } else {
          this.disabledBtns = []
        }
      },

      // 请求参数准备
      getPostData() {
        const status = this.currentOrderStatus
        const ctype = this.currentOrderCtype
        const BSXF = this.ctype.BSXF
        const BSZH = this.ctype.BSZH
        const ECHF = this.ctype.ECHF

        const formComponent = this.$refs.detailsForm
        const form = formComponent.form;
        let params = {
          orderid: this.baseInfo.orderid,
          characterId: this.baseInfo.characterId,
          ctype: this.baseInfo.ctype,
          processId: this.baseInfo.processId,
          taskId: this.baseInfo.taskId,
          result: this.opnCode
        }
        if (this.isYYZX) {
          if (this.disparageType === BSXF) {
            params.derogatoryCategories = form.derogatoryCategories
            params.derogatoryReason = this.isFromMessage ? this.currentOrderDetails.derogatoryReason : form.derogatoryReason
          }
        }
        if (this.isXSZB) {
          if((ctype === BSXF || ctype === ECHF) && status === '1') {
            params.toGroupId = form.branchCompanyId
          }
        }
        params.suggestion = form.suggestion
        return params
      },

      // 把对象转成查询字符串
      jsonToQueryStr(data) {
        let result = []
        for (let key in data) {
          data.hasOwnProperty(key) && result.push(`${key}=${data[key]}`)
        }
        return result.join('&')
      },

      // 审批
      post(validateSuggestion) {
        this.$refs.detailsForm.validate().then((res) => {
          const type = this.disparageType
          const fns1 = [userOpnCenterNext, '', userOpnCenterVisit]
          const fns2 = [saleHQNext, '', saleHQVisit]
          const fns = this.isYYZX ? fns1 : fns2
          const request = fns[type]
          const data = this.getPostData()
          if (validateSuggestion && !data.suggestion) {
            this.$message.closeAll()
            this.$message.warning('请填写意见！')
            return false
          }
          const params = data
          if (typeof request !== 'function') {
            return
          }
          this.loading = true
          request(params).then(res => {
            this.$emit('update')
            this.$message({
              duration: 1000,
              message: res.data.code === 1 ? '操作成功！' : '操作失败！',
              type: res.data.code === 1 ? 'success' : 'error',
              onClose: () => {
                this.resetForm()
              }
            })
          }).catch(() => {}).finally(err => {
            this.loading = false
            this.detailsFormValidate.branchCompany = true
            this.$emit('update:show', false)
          })

        }).catch((err) => {
          this.$message.closeAll()
          this.$message.warning('请填写表单！')
          return false
        })
      },

      autoFillBranchCompany() {
        this.$refs.detailsForm.autoFillBranchCompany(this.baseInfo.branchCompany)
      },

      resetForm() {
        this.$refs.detailsForm.resetForm()
      },

      // 休眠
      handleSleep() {
        this.opnCode = 2
        this.post(1)
      },
      // 驳回
      handleReject() {
        this.detailsFormValidate.branchCompany = false
        this.opnCode = this.isYYZX && this.disparageType === this.ctype.BSXF ? 7 : 0
        this.$nextTick(() => {
          this.post(1)
        })
      },
      // 下发
      handleNext() {
        this.opnCode = 1
        this.post(this.isYYZX && this.disparageType === this.ctype.ECHF)
      },
      // 完成
      handleDone() {
        this.opnCode = 8
        this.post()
      },
      // 通过
      handleAdopted() {
        this.opnCode = 1
        this.post()
      }
    },
    watch: {
      show(value) {
        value && this.$nextTick(() => {
          this.autoFillBranchCompany()
        })
      }
    }
  }
</script>

<style scoped>

</style>
